package com.letwal.cmcvnd.earn

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.bumptech.glide.Glide
import com.ocnyang.pagetransformerhelp.cardtransformer.AlphaAndScalePageTransformer
import com.letwal.cmcvnd.R
import com.letwal.cmcvnd.adata.RevDataBanner
import com.letwal.cmcvnd.adata.home.getInviteFriendEarn.ReqGetInviteFriendEarn
import com.letwal.cmcvnd.aviewmodel.ConfigViewModel
import com.letwal.cmcvnd.aviewmodel.HomeViewModel
import com.letwal.cmcvnd.base.BaseActivity
import com.letwal.cmcvnd.base.BaseFragment
import com.letwal.cmcvnd.data.ReqBase
import com.letwal.cmcvnd.databinding.FragmentEarnBinding
import com.letwal.cmcvnd.earn.adapter.EarnLevelPageAdapter
import com.letwal.cmcvnd.extend.*
import com.letwal.cmcvnd.home.repo.HomeCoinManager
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.indicator.CircleIndicator


/** earn 页 */
class EarnFragment : BaseFragment() {

    //布局binding
    private lateinit var mFragmentBinding: FragmentEarnBinding

    //适配器
    private lateinit var mEarnLevelPageAdapter: EarnLevelPageAdapter

    // home viewModel
    private val mHomeViewModel by lazy {
        ViewModelProvider(this)[HomeViewModel::class.java]
    }

    //Config ViewModel
    private val mConfigViewModel by lazy {
        ViewModelProvider(this)[ConfigViewModel::class.java]
    }

    override fun onBindingViewModel(): List<ViewModel> {
        val list = mutableListOf<ViewModel>()
        list.add(mHomeViewModel)
        list.add(mConfigViewModel)
        return list
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View {
        mFragmentBinding =
            FragmentEarnBinding.inflate(inflater, container, false)
        return mFragmentBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        try {
            //初始化刷新组件
            initRefreshUI()

            //监听返回
            onHandleLiveDataCallback()

            //初始化
            mEarnLevelPageAdapter =
                EarnLevelPageAdapter(requireContext(), mHomeViewModel.mTransferInEarnList)
            mEarnLevelPageAdapter.setItemClickListener { _, _ ->
                (requireActivity() as BaseActivity).startToTotalEarnActivity()
            }

            mFragmentBinding.viewPagerEarnTransferInEarn.offscreenPageLimit = (3)
            mFragmentBinding.viewPagerEarnTransferInEarn.pageMargin = 20
            mFragmentBinding.viewPagerEarnTransferInEarn.setPageTransformer(
                true,
                AlphaAndScalePageTransformer()
            )
            mFragmentBinding.viewPagerEarnTransferInEarn.adapter = mEarnLevelPageAdapter

            //点击my wallet
            mFragmentBinding.topNavBarEarn.setOnActionClickListener { action ->
                if (action == R.integer.NavbarActionLeft) {
                    (requireActivity() as BaseActivity).startToMyWalletActivity()
                }
            }

            //点击transfer rules
            mFragmentBinding.textEarnTransferInEarnRules.setOnClickListener {
                (requireActivity() as BaseActivity).startToTransferEarnRulesActivity()
            }

            //点击withdraw
            mFragmentBinding.llEarnWithdraw.setOnClickListener {
                (requireActivity() as BaseActivity).startToWithdrawActivity()
            }

            //点击transfer-receive
            mFragmentBinding.llEarnReceive.setOnClickListener {
                (requireActivity() as BaseActivity).startToReceiveActivity()
            }

            //点击invite-withdraw
            mFragmentBinding.textEarnInvitationWithdraw.addUnderLine()
            mFragmentBinding.textEarnInvitationWithdraw.setOnClickListener {
                (requireActivity() as BaseActivity).startToWithdrawForInviteEarnActivity()
            }

            //点击invite
            mFragmentBinding.llEarnInvite.setOnClickListener {
                (requireActivity() as BaseActivity).startToInviteActivity()
            }

            //点击invite rules
            mFragmentBinding.textEarnInviteEarnRules.setOnClickListener {
                (requireActivity() as BaseActivity).startToInviteEarnRulesActivity()
            }

            //点击invite detail
            mFragmentBinding.rlEarnInviteEarn.setOnClickListener {
                (requireActivity() as BaseActivity).startToInviteDetailActivity()
            }

            //更新标题
            mFragmentBinding.topNavBarEarn.setCenterText(HomeCoinManager.mGlobalNameLiveData.value)

            //先获取配置
            getRechargeIncomeConfig()

            //获取转入收益总览
            //getTransferInEarn()

            //获取邀请好友收益总览
            //getInviteFriendEarn()

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onResume() {
        super.onResume()

//        HomeCoinManager.earnCoinType?.let {
//            //获取转入收益总览
//            getTransferInEarn()
//
//            //获取邀请好友收益总览
//            getInviteFriendEarn()
//        }
    }

    /** 初始化底部banner */
    private fun initBottomBanner() {
        val testList = mutableListOf<RevDataBanner>()
        mFragmentBinding.bannerEarnBottom.addBannerLifecycleObserver(this)
            .indicator = CircleIndicator(requireActivity())
        mFragmentBinding.bannerEarnBottom.setAdapter(object :
            BannerImageAdapter<RevDataBanner>(testList as List<RevDataBanner>) {
            override fun onBindView(
                holder: BannerImageHolder,
                data: RevDataBanner,
                position: Int,
                size: Int
            ) {
                Glide.with(holder.itemView)
                    .load(data.imageUrl)
//                    .apply(RequestOptions.bitmapTransform(RoundedCorners(30)))
                    .into(holder.imageView)
            }
        })
            .addBannerLifecycleObserver(this)
            .indicator = CircleIndicator(requireActivity())
    }

    /** 监听live data 返回 */
    @SuppressLint("NotifyDataSetChanged", "SetTextI18n")
    private fun onHandleLiveDataCallback() {
        HomeCoinManager.mGlobalNameLiveData.observe(viewLifecycleOwner) {
            //更新标题
            mFragmentBinding.topNavBarEarn.setCenterText(it)
        }

        HomeCoinManager.mGlobalCoinTypeLiveData.observe(viewLifecycleOwner) {
            stopRefreshState()
            it?.let {
                //获取转入收益总览
                getTransferInEarn()

                //获取邀请好友收益总览
                getInviteFriendEarn()
            }
        }

        mConfigViewModel.onGetRechargeIncomeConfigLiveData.observe(viewLifecycleOwner) {
            stopRefreshState()
            if (it.isSuccess) {
                it.getOrNull()?.let { result ->
                    //更新配置
                    for (index in 0 until result.size) {
                        val config = result[index]
                        val item = mHomeViewModel.mTransferInEarnList[index]
                        item.nextAmount = config.max
                        item.level = config.level
                        item.incomeRate = config.rate
                    }
                }

                //获取转入收益总览
                getTransferInEarn()

                //获取邀请好友收益总览
                getInviteFriendEarn()
            }
        }

        mHomeViewModel.onGetTransferInEarnLiveData.observe(viewLifecycleOwner) {
            stopRefreshState()
            if (it.isSuccess) {
                it.getOrNull()?.let { result ->
                    var scrollIndex = 0
                    for (index in 0 until mHomeViewModel.mTransferInEarnList.size) {
                        val item = mHomeViewModel.mTransferInEarnList[index]
                        if (item.level?.equals(result.level, true) == true) {
                            scrollIndex = index
                            item.isValidData = true
                            item.incomeRate = result.incomeRate
                            item.nextAmount = result.nextAmount

                            //公共数据
                            item.remindTimes = result.remindTimes
                            item.todayAmount = result.todayAmount
                            item.todayIncome = result.todayIncome
                            item.totalTimes = result.totalTimes

                        } else {
                            item.isValidData = false

                            //公共数据
                            item.remindTimes = result.remindTimes
                            item.todayAmount = result.todayAmount
                            item.todayIncome = result.todayIncome
                            item.totalTimes = result.totalTimes
                        }
                    }
                    mEarnLevelPageAdapter.notifyDataSetChanged()
                    mFragmentBinding.viewPagerEarnTransferInEarn.setCurrentItem(scrollIndex, true)
                }
            }
        }

        mHomeViewModel.onGetInviteFriendEarnLiveData.observe(viewLifecycleOwner) {
            stopRefreshState()
            if (it.isSuccess) {
                it.getOrNull()?.let { result ->
                    mFragmentBinding.textEarnInvitationRewardsRatioValue.text =
                        result.incomeRate.toFinancePercentString()
                    mFragmentBinding.textEarnInvitationRewardsValue.text =
                        result.myIncome.toFinanceString() + " USDT"
                    mFragmentBinding.textEarnInvitationInvitedNumberValue.text =
                        result.inviteNum.toString()
                    mFragmentBinding.textEarnInvitationFriendsEarnValue.text =
                        result.friendIncome.toFinanceString() + " USDT"
                }
            }
        }
    }

    /** 获取转入收益总览 */
    private fun getTransferInEarn() {
        HomeCoinManager.mGlobalCoinTypeLiveData.value?.let {
            val reqGetInviteFriendEarn1 = ReqGetInviteFriendEarn(coinType = it)
            reqGetInviteFriendEarn1.showLoading = false
            mHomeViewModel.getTransferInEarn(reqGetInviteFriendEarn1)
        }
    }

    /** 获取邀请好友收益总览 */
    private fun getInviteFriendEarn() {
        HomeCoinManager.mGlobalCoinTypeLiveData.value?.let {
            val reqGetInviteFriendEarn2 = ReqGetInviteFriendEarn(coinType = it)
            reqGetInviteFriendEarn2.showLoading = false
            mHomeViewModel.getInviteFriendEarn(reqGetInviteFriendEarn2)
        }
    }

    /** 获取配置 */
    private fun getRechargeIncomeConfig() {
        val reqBase = ReqBase()
        reqBase.showLoading = false
        mConfigViewModel.getRechargeIncomeConfig(reqBase)
    }

    /** 初始化下拉刷新 */
    private fun initRefreshUI() {
        connectSwipeRefreshLayout(mFragmentBinding.swipeRefresh) {
            //先获取配置
            getRechargeIncomeConfig()
        }
    }
}